#include "../../../vcd-common-api/vcd-common.h"
#include "../../vcd-message-dialog.h"
#include "vcd-sound.h"
#include "../../../vcd-common-api/vcd-conf/vcd-conf.h"
#include "../../../vcd-common-api/vcd-util.h"

GtkWidget *scale;
GtkWidget *g_sound_card_profile_combo;
GtkWidget *g_sound_card_name_combo;
char g_sound_card_name[220] = {0};

void volume(GtkWidget *Scale);
void change_sound_card_profile(void);
char *get_current_used_sound_profile(void);
char *get_sound_card_profile(int n);
gboolean get_sound_card_name(void);
double get_nowvolume(void);
char *get_sink_volume_name(void);
gboolean set_sound_combo_card_name(void);
gboolean set_sound_combo_card_profile(void);
void note_sound_card_name(const char *card_name);

//此处应该是list_card显示两张卡的时候才会被用到，暂时保留代码，等待有两张显示卡的情况出现进行调试
gboolean get_sound_card_name(void)
{
    // memset(g_sound_card_name, 0, 220);
    // char sound_name[220];
    // FILE *pf = fopen("/opt/virt-viewer/sound_name.txt", "r");
    // if (pf == NULL)
    //     return FALSE;
    // if (!fgets(sound_name, sizeof(sound_name), pf)) {
    //     fclose(pf);
    //     pf = NULL;
    //     return FALSE; 
    // }
    // strncpy(g_sound_card_name, sound_name, sizeof(g_sound_card_name));
    // M_DEBUG("sound_card_name = %s", g_sound_card_name);
    // fclose(pf);
    // pf = NULL;
    // return TRUE;
    struct vcd_conf* tmp_vcd_conf = g_vcd_conf;
    if (tmp_vcd_conf->sound_card_name == NULL || strlen(tmp_vcd_conf->sound_card_name) == 0)
        return FALSE;

    strncpy(g_sound_card_name, tmp_vcd_conf->sound_card_name, sizeof(g_sound_card_name));
    return TRUE;
}

void note_sound_card_name(const char *card_name)
{
    struct vcd_conf* tmp_vcd_conf = g_vcd_conf;
    strncpy(tmp_vcd_conf->sound_card_name, card_name, sizeof(tmp_vcd_conf->sound_card_name));
    update_vcd_conf();

    // FILE *fp = fopen("/opt/virt-viewer/sound_name.txt", "w+");
    // if(fp == NULL){
    //     return;
    // }
    // fputs(card_name, fp);
    // fclose(fp);
    // fp = NULL;
}

char *get_sound_card_profile(int n)
{
    char *line_buff = (char *)malloc(300 * sizeof(char));
    if (NULL == line_buff) {
        M_DEBUG("malloc error");
    }
#ifndef __linux__
    return line_buff;
#endif
    char line_buf[256] = {0};
    FILE *pf;
    char cmd[500] = {0};
#ifdef ENGLISH
    sprintf(cmd, "pactl list cards|sed -n -e '/%s/,/Card #/p'|grep -A 100 Profiles:|grep -B 100 \"off: Off\"|grep \"available: yes\"|cut -d \" \" -f1|sed -n 's/:$//p'",
            gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo));
#else
    sprintf(cmd, "pactl list cards|sed -n -e '/%s/,/卡 #/p'|grep -A 100 配置文件：|grep -B 100 \"off: 关\"|cut -d \" \" -f1|sed -n 's/:$//p'",
            gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo));
#endif
    M_DEBUG("%s", cmd);
    pf = popen(cmd, "r");
    if (NULL == pf)
        return line_buff;

    int i = 0;
    int j = 0;
    for (i = 0; i < n + 2; i++) //print from second
    {
        strcpy(line_buf, "");
        if (!fgets(line_buf, 256, pf))
        {
            M_DEBUG("get_sound_card_profile error");
            pclose(pf);
            return line_buff;
        }
        for (j = 0; j < strlen(line_buf); j++) //delete the head two char
        {
            line_buf[j] = line_buf[j + 2];
        }
    }
    pclose(pf);
    line_buf[strlen(line_buf) - 1] = 0;
    strcpy(line_buff, line_buf);
    return line_buff;
}

double get_nowvolume(void)
{
    char cmd[1000];
    char *card_name;
    card_name = gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo);

#ifdef ENGLISH
    snprintf(cmd, sizeof(cmd), "pactl list sinks|sed -n -e '/%s/,/Profiles:/p'|grep \"Volume: front-left\"|awk '{print $5}'|cut -d %% -f1",
            strstr(card_name, "."));
#else
    snprintf(cmd, sizeof(cmd), "pactl list sinks|sed -n -e '/%s/,/信宿 #/p'|grep \"音量：front-left\"|awk '{print $4}'|cut -d %% -f1",
            strstr(card_name, "."));
#endif
    M_DEBUG("%s", cmd);

    char* str = exe_command(cmd, NULL);
    if(str == NULL){
        M_DEBUG("popen pactl error!");
        return 0.0f;
    }
    return atof(str);
}


char *get_sink_volume_name(void)
{
    char *res = (char *)malloc(200 * sizeof(char));
    FILE *pf;
    char cmd[500];
    char card_name[220];

    strcpy(card_name, gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo));
#ifdef ENGLISH
    sprintf(cmd, "pactl list sinks|grep %s|grep Name|cut -d ' ' -f2", strstr(card_name, "."));
#else
    sprintf(cmd, "pactl list sinks|grep %s|grep 名称：|cut -d '：' -f2", strstr(card_name, "."));
#endif
    M_DEBUG("%s", cmd);
    pf = popen(cmd, "r");
    if (pf == NULL)
    {
        M_DEBUG("popen pactl error!");
        return res;
    } else
    {
        if (!fgets(res, 500, pf))
        {
            M_DEBUG("get_sink_volume_name error");
        }
        res[strlen(res) - 1] = 0;
        pclose(pf);
        return res;
    }
}

void volume(GtkWidget *Scale)
{
#ifndef __linux__
    return;
#endif
    char sound_cmd[500] = {0};
    char *sink_num = get_sink_volume_name();
    gdouble sound = gtk_range_get_value((GtkRange *)Scale);
    sprintf(sound_cmd, "pactl set-sink-volume %s %d%%", sink_num, (int)sound);
    M_DEBUG("%s", sound_cmd);
    int res = system(sound_cmd);
    if (res != 0) {
        M_DEBUG("set-sink-volume  error");
    }
    if (sink_num != NULL) {
        free(sink_num);
        sink_num = NULL;
    }
}

char *get_current_used_sound_profile(void)
{
    char cmd[500] = {0};
    gchar *card_name = gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo);
#ifdef ENGLISH
    snprintf(cmd,sizeof(cmd), "pactl list cards|sed -n -e '/%s/,/Card #/p'|grep \"Active Profile:\"|cut -d \" \" -f3",card_name);
#else
    snprintf(cmd,sizeof(cmd), "pactl list cards|sed -n -e '/%s/,/卡 #/p'|grep 活动配置：|cut -d \"：\" -f2",card_name);
#endif
    M_DEBUG("%s", cmd);

    char *res = exe_command(cmd, NULL);
    if(res == NULL){
        message_box("   获取当前声卡与音量失败！   ");
        return NULL;
    }
    return res;

}

void change_sound_card_profile(void)
{
#ifndef __linux__
    return;
#endif
    char *card_name;
    char *current_profile;

    card_name = gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo);
    current_profile = gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_profile_combo);

    /* 如果点击按钮之后发现选项和之前选项没有区别就直接返回不做任何修改 */
    char *current_used_profilr = get_current_used_sound_profile();
    M_DEBUG(current_profile);
    M_DEBUG(current_used_profilr);
    if (current_used_profilr == NULL)
        return;

    if (strcmp(current_profile, current_used_profilr) != 0 || strcmp(card_name, g_sound_card_name) != 0)
    {
        char cmd[1024];
        snprintf(cmd, sizeof(cmd), "pactl set-card-profile %s \"%s\"", card_name, current_profile);
        int res = system(cmd);
        M_DEBUG("cmd:%s, res=%d\n", cmd, res);
        if (res == 0) {
            message_box("     设置成功!     ");
        } else {
            message_box("     设置失败!     ");
            return;
        }

        double nowvolume = get_nowvolume() / 100;
        gtk_range_set_value((GtkRange *)scale, nowvolume * 100);
    }
    note_sound_card_name(card_name);
    M_DEBUG(card_name);
    M_DEBUG(g_sound_card_name);
}

/* pactl list cards 显示名称 */
gboolean set_sound_combo_card_name(void)
{
    gtk_combo_box_text_remove_all((GtkComboBoxText *)(g_sound_card_name_combo));
    char line_buff[1024];
#ifdef ENGLISH
    const char *cmd = "pactl list cards|grep Name|awk {'print $2'}";
#else
    const char *cmd = "pactl list cards|grep 名称|cut -d '：' -f2";
#endif
    M_DEBUG("%s", cmd);
    FILE *pf = popen(cmd, "r");
    if (pf == NULL)
        return FALSE;
    if (strlen(g_sound_card_name) != 0)
        gtk_combo_box_text_append((GtkComboBoxText *)g_sound_card_name_combo, NULL, g_sound_card_name);

    while (fgets(line_buff, sizeof(line_buff), pf))
    {
        line_buff[strlen(line_buff) - 1] = 0;
        if (strcmp(g_sound_card_name, line_buff) != 0)
            gtk_combo_box_text_append((GtkComboBoxText *)g_sound_card_name_combo, NULL, line_buff);
    }
    fclose(pf);

    gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)g_sound_card_name_combo), 0);
    return TRUE;
}

gboolean set_sound_combo_card_profile(void)
{
#ifndef __linux__
    return FALSE;
#endif
    if (-1 == gtk_combo_box_get_active((GtkComboBox *)g_sound_card_name_combo)) {
        M_DEBUG("get g_sound_card_name_combo error!");
        return FALSE;
    }

    int sound_cards_profile_num = 0;
    char line_buff[500];
    FILE *pf3;
    char cmd[500] = {0};
    char card_name[220] = {0};
    strcpy(card_name, gtk_combo_box_text_get_active_text((GtkComboBoxText *)g_sound_card_name_combo));
#ifdef ENGLISH
    sprintf(cmd, "pactl list cards|sed -n -e '/%s/,/Card #/p'|grep -A 100 Profiles:|grep -B 100 \"off: Off\"|grep \"available: yes\"|cut -d \" \" -f1|sed -n 's/:$//p'",
            card_name);
#else
    sprintf(cmd, "pactl list cards|sed -n -e '/%s/,/卡 #/p'|grep -A 100 配置文件：|grep -B 100 \"off: 关\"|cut -d \" \" -f1|sed -n 's/:$//p'",
            card_name);
#endif
    M_DEBUG("%s", cmd);
    pf3 = popen(cmd, "r");
    if (pf3 == NULL)
        return FALSE;

    while (fgets(line_buff, 500, pf3)) {
        sound_cards_profile_num++;
    }
    sound_cards_profile_num -= 2;
    pclose(pf3);

    int i;
    char *sound_card_buf = NULL;
    char *current_used_sound_device = NULL;
    gtk_combo_box_text_remove_all((GtkComboBoxText *)(g_sound_card_profile_combo));
    current_used_sound_device = get_current_used_sound_profile();
    gtk_combo_box_text_append((GtkComboBoxText *)g_sound_card_profile_combo, NULL, current_used_sound_device);
    for (i = 0; i < sound_cards_profile_num; i++)
    {
        sound_card_buf = get_sound_card_profile(i);
        if (strcmp(sound_card_buf, current_used_sound_device) != 0)
            gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)g_sound_card_profile_combo), NULL, sound_card_buf);
        if (sound_card_buf != NULL)
        {
            free(sound_card_buf);
            sound_card_buf = NULL;
        }
    }
    if (current_used_sound_device != NULL)
    {
        free(current_used_sound_device);
        current_used_sound_device = NULL;
    }
    gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)g_sound_card_profile_combo), 0);

    double nowvolume = get_nowvolume() / 100;
    gtk_range_set_value((GtkRange *)scale, nowvolume * 100);
    return TRUE;
}

gboolean set_sound_combo(void)
{
#ifdef __linux__
    if (!get_sound_card_name())
        M_DEBUG("get record sound card name failed!");
    if (!set_sound_combo_card_name())
        M_DEBUG("set sound card name failed");
#endif
    return FALSE;
}

GtkWidget* get_sound_setting_fix(void)
{
    GtkWidget *fix_sound = gtk_fixed_new();

    GtkWidget *label_sound_card_name = gtk_label_new("音频名字");
    GtkWidget *label_sound_card_profile = gtk_label_new("音频接口");
    GtkWidget *label_sound_volume = gtk_label_new(" 音量");

    g_sound_card_profile_combo = gtk_combo_box_text_new();
    gtk_widget_set_size_request(g_sound_card_profile_combo, 377, 20);

    g_sound_card_name_combo = gtk_combo_box_text_new();
    gtk_widget_set_size_request(g_sound_card_name_combo, 377, 20);

    GtkWidget *btn_change_sound = gtk_button_new_with_label("应用");
    gtk_button_set_relief(GTK_BUTTON(btn_change_sound), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_change_sound, 70, 20);

    scale = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, 100, 1);
    gtk_widget_set_size_request(scale, 372, 20);

    gtk_fixed_put((GtkFixed *)fix_sound, label_sound_card_name,    30,  62);
    gtk_fixed_put((GtkFixed *)fix_sound, g_sound_card_name_combo,  106, 55);
    gtk_fixed_put((GtkFixed *)fix_sound, label_sound_card_profile, 30,  112);
    gtk_fixed_put((GtkFixed *)fix_sound, g_sound_card_profile_combo, 106, 105);
    gtk_fixed_put((GtkFixed *)fix_sound, btn_change_sound,     495, 105);
    gtk_fixed_put((GtkFixed *)fix_sound, label_sound_volume,   54,  163);
    gtk_fixed_put((GtkFixed *)fix_sound, scale,                98,  142);

    g_signal_connect(G_OBJECT(btn_change_sound), "clicked", G_CALLBACK(change_sound_card_profile), NULL);
    g_signal_connect(G_OBJECT(scale), "value_changed", G_CALLBACK(volume), NULL);
    /* 每次初始化g_sound_card_name_combo，都会触发这个信号(和手动点击一样)， */
    g_signal_connect(G_OBJECT(g_sound_card_name_combo), "changed", G_CALLBACK(set_sound_combo_card_profile), NULL);

    set_css(btn_change_sound, "button{ color:white;"
                              "background:rgb(53,126,169);"
                              "border:1px solid rgb(40,94,142);"
                              "border-radius:0px}");
    set_css(btn_change_sound, "button:hover{border-radius:0px;background: #3070a9}");

    return fix_sound;
}
